import { reactive } from "vue";
import type { Comment, CommentReply, CommentLike } from "../types/comment";
import type { Editor } from "@tiptap/vue-3";
import { removeCommentMark, updateCommentMarkStyle } from "../utils/commentEditor";

// 批注存储
export const commentStore = reactive<{
  comments: Map<string, Comment>;
  activeCommentId: string | null;
  panelVisible: boolean;
}>({
  comments: new Map(),
  activeCommentId: null,
  panelVisible: false,
});

// 批注操作
export const commentActions = {
  // 添加批注
  addComment(comment: Comment) {
    commentStore.comments.set(comment.id, comment);
  },

  // 更新批注
  updateComment(commentId: string, updates: Partial<Comment>) {
    const comment = commentStore.comments.get(commentId);
    if (comment) {
      Object.assign(comment, updates);
      comment.updatedAt = new Date().toISOString();
    }
  },

  // 删除批注
  deleteComment(commentId: string, editor?: Editor) {
    commentStore.comments.delete(commentId);
    if (commentStore.activeCommentId === commentId) {
      commentStore.activeCommentId = null;
    }
    // 如果提供了editor实例，从编辑器移除标记
    if (editor) {
      removeCommentMark(editor, commentId);
    }
  },

  // 添加回复
  addReply(commentId: string, reply: CommentReply) {
    const comment = commentStore.comments.get(commentId);
    if (comment) {
      if (!comment.replies) {
        comment.replies = [];
      }
      comment.replies.push(reply);
      comment.updatedAt = new Date().toISOString();
    }
  },

  // 解决/取消解决批注
  toggleResolve(commentId: string, resolvedBy: string, editor?: Editor) {
    const comment = commentStore.comments.get(commentId);
    if (comment) {
      comment.isResolved = !comment.isResolved;
      if (comment.isResolved) {
        comment.resolvedAt = new Date().toISOString();
        comment.resolvedBy = resolvedBy;
      } else {
        comment.resolvedAt = undefined;
        comment.resolvedBy = undefined;
      }
      comment.updatedAt = new Date().toISOString();
      // 如果提供了editor实例，更新编辑器中的标记样式
      if (editor) {
        updateCommentMarkStyle(editor, commentId, comment.isResolved);
      }
    }
  },

  // 设置活动批注
  setActiveComment(commentId: string | null) {
    commentStore.activeCommentId = commentId;
  },

  // 切换面板显示
  togglePanel() {
    commentStore.panelVisible = !commentStore.panelVisible;
  },

  // 检查面板是否可见
  isPanelVisible(): boolean {
    return commentStore.panelVisible;
  },

  // 获取批注
  getComment(commentId: string): Comment | undefined {
    return commentStore.comments.get(commentId);
  },

  // 获取所有批注
  getAllComments(): Comment[] {
    return Array.from(commentStore.comments.values());
  },

  // 获取指定位置的批注
  getCommentsByPosition(from: number, to: number): Comment[] {
    return Array.from(commentStore.comments.values()).filter(
      (comment) =>
        comment.position.from === from && comment.position.to === to
    );
  },

  // 更新回复
  updateReply(
    commentId: string,
    replyId: string,
    content: string,
    editor?: Editor
  ) {
    const comment = commentStore.comments.get(commentId);
    if (comment?.replies) {
      const reply = comment.replies.find((r) => r.id === replyId);
      if (reply) {
        reply.content = content;
        reply.updatedAt = new Date().toISOString();
        reply.isEdited = true;
        comment.updatedAt = new Date().toISOString();
      }
    }
  },

  // 删除回复
  deleteReply(
    commentId: string,
    replyId: string,
    deletedBy: string,
    editor?: Editor
  ) {
    const comment = commentStore.comments.get(commentId);
    if (comment?.replies) {
      const reply = comment.replies.find((r) => r.id === replyId);
      if (reply) {
        reply.isDeleted = true;
        reply.deletedAt = new Date().toISOString();
        reply.deletedBy = deletedBy;
        comment.updatedAt = new Date().toISOString();
      }
    }
  },

  // 切换回复点赞/点踩
  toggleReplyLike(
    commentId: string,
    replyId: string,
    userId: string,
    likeType: "like" | "dislike" | null,
    editor?: Editor
  ) {
    const comment = commentStore.comments.get(commentId);
    if (comment?.replies) {
      const reply = comment.replies.find((r) => r.id === replyId);
      if (reply) {
        if (!reply.likes) {
          reply.likes = [];
        }
        if (!reply.likeCount) {
          reply.likeCount = 0;
        }
        if (!reply.dislikeCount) {
          reply.dislikeCount = 0;
        }

        // 查找用户已有的点赞
        const existingLikeIndex = reply.likes.findIndex(
          (like) => like.userId === userId
        );

        if (likeType === null) {
          // 取消点赞/点踩
          if (existingLikeIndex >= 0) {
            const existingLike = reply.likes[existingLikeIndex];
            if (existingLike.type === "like") {
              reply.likeCount = Math.max(0, (reply.likeCount || 0) - 1);
            } else {
              reply.dislikeCount = Math.max(0, (reply.dislikeCount || 0) - 1);
            }
            reply.likes.splice(existingLikeIndex, 1);
          }
        } else {
          // 添加或更新点赞
          if (existingLikeIndex >= 0) {
            const existingLike = reply.likes[existingLikeIndex];
            // 如果类型相同，则取消；如果不同，则切换
            if (existingLike.type === likeType) {
              // 取消
              if (likeType === "like") {
                reply.likeCount = Math.max(0, (reply.likeCount || 0) - 1);
              } else {
                reply.dislikeCount = Math.max(0, (reply.dislikeCount || 0) - 1);
              }
              reply.likes.splice(existingLikeIndex, 1);
            } else {
              // 切换类型
              if (existingLike.type === "like") {
                reply.likeCount = Math.max(0, (reply.likeCount || 0) - 1);
                reply.dislikeCount = (reply.dislikeCount || 0) + 1;
              } else {
                reply.dislikeCount = Math.max(0, (reply.dislikeCount || 0) - 1);
                reply.likeCount = (reply.likeCount || 0) + 1;
              }
              existingLike.type = likeType;
            }
          } else {
            // 新增点赞
            reply.likes.push({
              userId,
              type: likeType,
              createdAt: new Date().toISOString(),
            });
            if (likeType === "like") {
              reply.likeCount = (reply.likeCount || 0) + 1;
            } else {
              reply.dislikeCount = (reply.dislikeCount || 0) + 1;
            }
          }
        }

        comment.updatedAt = new Date().toISOString();
      }
    }
  },
};

